<template>
  <CustomTableCard 
    footer
    temporary 
    actions 
    :total="total" 
    :page.sync="queryParams.page" 
    :limit.sync="queryParams.limit" 
    :width="600"
    :showDrawer.sync="showDrawer" 
    @on-page="getList" 
    @cancel="handleCancel"
    @ok="handleOk"
    :title="baseInfo.id ? $t('actions.edit') : $t('actions.add')">
    <div slot="header">
      <v-row>
        <v-col cols="2">
          <v-select
            v-model="queryParams.type"
            :items="dictTypeListToArray"
            label="选择字典类型"
            item-text="name"
            item-value="value"
            dense
            outlined
            hide-details
            clearable
            @change="getList(1)"
          ></v-select>
        </v-col>
        <v-col cols="3">
          <v-text-field
            v-model.trim="queryParams.keyword"
            :label="$t('placeholder.keyword')"
            outlined
            dense
            hide-details
            clearable
            @keyup.enter.native="getList(1)"
          ></v-text-field>
        </v-col>
        <v-col>
          <v-btn color="info" class="mr-3" @click="getList(1)">{{ $t('actions.search') }}</v-btn>
        </v-col>
        <v-col cols="1" class="text-right">
          <v-btn color="primary" @click="showDrawer = true">{{ $t('actions.add') }}</v-btn>
        </v-col>
      </v-row>
    </div>
    <el-table
      v-loading="listLoading"
      v-auto-height
      :height="tableHeight"
      :data="tableData"
      stripe
      fit
      @selection-change="handleSelectionChange"
      style="width: 100%">
      <el-table-column
        type="selection"
        align="center"
        width="56">
      </el-table-column>
      <el-table-column
        fixed
        prop="type"
        :label="$t('system.fields.type')">
        <template slot-scope="scope">
          <span>{{dictTypeList[scope.row.type]}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="key"
        :label="$t('system.fields.key')">
      </el-table-column>
      <el-table-column
        prop="value"
        :label="$t('system.fields.value')">
      </el-table-column>
      <el-table-column
        fixed="right"
        prop="status"
        :label="$t('system.fields.status')"
        width="140">
        <template slot-scope="{ row }">
          <v-switch class="mt-0" dense hide-details :input-value="row.status == 1" :label="row.status == 1 ? '已激活' : '已锁定'" @change="setStatus(row)"></v-switch>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        :label="$t('system.fields.action')"
        align="center"
        width="180">
        <template slot-scope="{ row }">
          <v-btn class="mr-2" small color="primary" outlined @click="handleEdit(row)">{{ $t('actions.edit') }}</v-btn>
          <!-- <v-btn small color="warning" outlined @click="handleRmove(row)">{{ $t('actions.delete') }}</v-btn> -->
        </template>
      </el-table-column>
    </el-table>
    <div slot="actions">
      <v-btn small color="success" :disabled="!multipleSelection.length" class="mr-2" @click="setStatusAll(1)">{{ $t('actions.open') }}</v-btn>
      <v-btn small color="warning" :disabled="!multipleSelection.length" @click="setStatusAll(2)">{{ $t('actions.close') }}</v-btn>
    </div>
    <section slot="drawer" class="pa-3">
      <v-form
        ref="form"
        :lazy-validation="false"
      >
        <v-card class="mb-4">
          <v-card-text>
            <div class="d-flex align-center px-3">
              <label style="width: 140px" class="text-right pr-3"><small class="mr-1" style="color: red">({{$t('other.required')}})</small>{{ $t('system.fields.type') }}</label>
              <v-select
                v-model="baseInfo.type"
                :items="dictTypeListToArray"
                item-text="name"
                item-value="value"
                :rules="[rules.required]"
                required
              ></v-select>
            </div>
            <div class="d-flex align-center px-3">
              <label style="width: 140px" class="text-right pr-3">{{ $t('system.fields.key') }}</label>
              <v-text-field
                v-model="baseInfo.key"
                placeholder="请输入"
                clearable
              ></v-text-field>
            </div>
            <div class="d-flex align-center px-3">
              <label style="width: 140px" class="text-right pr-3"><small class="mr-1" style="color: red">({{$t('other.required')}})</small>{{ $t('system.fields.value') }}</label>
              <v-text-field
                v-model="baseInfo.value"
                placeholder="请输入"
                clearable
                :rules="[rules.required]"
                required
              ></v-text-field>
            </div>
          </v-card-text>
        </v-card>
      </v-form>
    </section>
  </CustomTableCard>
</template>

<script>
// @ is an alias to /src
import { mapState } from 'vuex'
import * as systemApi from '@/api/system'
import mixin from './mixin'

export default {
  name: 'datadict',
  mixins: [mixin],
  created() {
    if (this.dictTypeList.length < 1) {
      this.$store.dispatch('system/getDictTypeList')
    }
    this.getList()
    this.cloneFormData()
  },
  activated() {
    console.log('activated')
    this.getList()
  },
  deactivated() {
    console.log('deactivated')
  },
  computed: {
    ...mapState('system', ['dictTypeList']),
    dictTypeListToArray() {
      let arr = Object.entries(this.dictTypeList)
      return arr.map(item => {
        return {
          value: item[0],
          name: item[1]
        }
      })
    }
  },
  data() {
    return {
      tableHeight: 500,
      showDrawer: false,
      tableData: [{}],
      total: 0,
      listLoading: false,
      queryParams: {
        page: 1,
        limit: 20,
        keyword: '',
        type: ''
      },

      baseInfo: {
        id: undefined,
        type: '',
        key: '',
        value: ''
      },

      multipleSelection: [],

      rules: {
        required: value => !!value || 'required',
      }
    }
  },

  methods: {
    // 克隆数据 用于重置数据使用
    cloneFormData() {
      this._baseInfo = Object.assign({}, this.baseInfo)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取列表
    getList(page) {
      if (/\d+/.test(page)) {
        this.queryParams.page = page
      }
      this.listLoading = true
      systemApi.getDictList(this.queryParams).then(response => {
        this.tableData = response.data.data
        this.total = response.data.count
      }).finally(() => {
        this.listLoading = false
      })
    },
    // 编辑列表
    handleEdit(row) {
      this.showDrawer = true
      Object.assign(this.baseInfo, row)
    },
    // 删除列表
    // handleRmove(row) {
    //   this.$confirm(this.$t('peers.tips.delete'), this.$t('peers.others.tip'), {
    //     center: true,
    //     type: 'warning'
    //   }).then(() => {
    //     partnerApi.remove({id: [row.id]}).then(() => {
    //       this.$message.success('success')
    //       this.getList()
    //     })
    //   })
    // },
    // 批量设置状态
    setStatusAll(status) {
      let ids = this.multipleSelection.map(item => item.id)
      this.updateStatus({id: ids, status})
    },
    // 设置状态
    setStatus(row) {
      let status = row.status == 1 ? 2 : 1
      this.updateStatus({id: [row.id], status})
    },
    // 更新状态
    updateStatus(params) {
      systemApi.changeStatus(params).then(() => {
        this.$message.success('success')
        this.getList()
      })
    },
    // 右侧窗口关闭事件
    handleCancel() {
      this.resetForm()
    },
    // 重置表达数据和验证
    resetForm () {
      Object.assign(this.baseInfo, this._baseInfo)
      this.$refs.form.resetValidation()
    },
    // 右侧窗口确定事件
    handleOk() {
      // console.log(this.baseInfo)
      if(this.$refs.form.validate()) {
        if(this.baseInfo.id) {
          systemApi.updateDict(this.baseInfo).then(() => {
            this.$message.success('success')
            this.getList()
            this.showDrawer = false
          })
        } else {
          systemApi.createDict(this.baseInfo).then(() => {
            this.$message.success('success')
            this.getList(1)
            this.showDrawer = false
          })
        }
      }
    }
  }
}
</script>
